<?php
/**
 *
 * User: Robin
 * Date: 2019/11/12 0012
 * Email: 704289189@qq.com
 **/


namespace app\common\model;


use think\facade\Db;
use think\Model;

class BaseModel extends Model
{
    private static $errorMsg;
    private static $transaction = 0;
    private static $DbInstance = [];
    const DEFAULT_ERROR_MSG = '操作失败，请稍后再试!';

    /**
     * 设置错误信息
     * @param string $errorMsg
     * @param bool $rollback
     * @return bool
     */
    protected static function setErrorInfo($errorMsg = self::DEFAULT_ERROR_MSG,$rollback = false){
        if ($rollback) self::rollbackgTrans();
        self::$errorMsg = $errorMsg;
        return false;
    }

    /**
     * 获取错误信息
     * @param string $defaultMsg
     * @return string
     */
    public static function getErrorInfo($defaultMsg = self::DEFAULT_ERROR_MSG){
        return !empty(self::$errorMsg) ? self::$errorMsg:$defaultMsg;
    }

    /**
     * 开启事务
     */
    public static function beginTrans(){
       Db::startTrans();
    }
    /**
     * 提交事务
     */
    public static function commitTrans(){
        Db::commit();
    }
    /**
     * 关闭事务
     */
    public static function rollbackTrans(){
        Db::rollback();
    }

    /**
     * 根据结果提交回滚事务
     * @param $res
     */
    public static function checkTrans($res){
        if ($res){
            self::commitTrans();
        }else{
            self::rollbackTrans();
        }
    }

}